//
//  AppDelegate.m
//  JinYong_iOS_Store
//
//  Created by 王厚一 on 2017/10/17.
//  Copyright © 2017年 why. All rights reserved.
//

#import "HYAppDelegate.h"
#import "NavigationRootViewController.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "OrderViewController.h"

@interface HYAppDelegate () <JPUSHRegisterDelegate>

@property (nonatomic,strong) NavigationRootViewController *navigation;

@end

@implementation HYAppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.navigation = [[NavigationRootViewController alloc] initWithRootViewController:[[MainViewController alloc] init]];
    
    self.window.rootViewController = self.navigation;

    [self.window makeKeyAndVisible];
    
    [self checkLogin];//检查登录
    [self registerAPNS:launchOptions];//注册APNS
    [self backGroundPushReceived:launchOptions];//后台收到推送
    return YES;
}

#pragma mark - ----------------------检查登录--------------------------
- (void)checkLogin {
    if (!kUserLoginResult) {
        LoginViewController * vc = [[LoginViewController alloc] init];
        UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:vc];
        navi.navigationBar.hidden = YES;
        [self.window.rootViewController presentViewController:navi animated:YES completion:nil];   
    }else {
        sendNotification(NOTIFICATION_LOGINSUCCESS)
    }
}

- (void)backGroundPushReceived:(NSDictionary *)launchOptions {
    //app未运行时，收到推送消息
    NSDictionary *resultInfo = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if (resultInfo) {//推送进入APP
        NSLog(@"后台接收到信息");
        OrderViewController * vc = [[OrderViewController alloc] init];
        vc.orderType = HYOrderTypeUnselected;
        [self.navigation pushViewController:vc animated:YES];
    }
}

- (void)registerAPNS:(NSDictionary *)launchOptions {
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
//    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    
    [JPUSHService setupWithOption:launchOptions appKey:appKeyJPush
                          channel:CHANNEL
                 apsForProduction:FALSE
            advertisingIdentifier:nil];
}

//添加处理APNs通知回调方法请在AppDelegate.m实现该回调方法并添加回调方法中的代码
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"收到的推送消息 userinfo %@",userInfo);
    //跳转页面
    //判断应用是在前台还是后台
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        NSLog(@"前台接收到信息");
        //第一种情况前台运行
        NSArray * array = self.navigation.viewControllers;
        if (![array.lastObject isEqual:[OrderViewController class]]) {
            OrderViewController * vc = [[OrderViewController alloc] init];
            vc.orderType = HYOrderTypeUnselected;
            [self.navigation pushViewController:vc animated:YES];
        }

        
        //        [[NSNotificationCenter defaultCenter]postNotificationName:@"REFRESHYUJING" object:nil];
    }
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    
}

// 通过点击推送弹出的通知调用,包括前台和后台
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSLog(@"点击推送框");
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSArray * array = self.navigation.viewControllers;
        if (![array.lastObject isEqual:[OrderViewController class]]) {
            OrderViewController * vc = [[OrderViewController alloc] init];
            vc.orderType = HYOrderTypeUnselected;
            [self.navigation pushViewController:vc animated:YES];
        }

        [JPUSHService handleRemoteNotification:userInfo];
        
        
    }else {
        
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

//注册deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSString * registerid = [JPUSHService registrationID];
    if (registerid.length == 0) {
        //没有获得到_registerid
        registerid = @"";
    }
    
}

//推送失败提示
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    [CustomAlert showAlertWithController:self.navigation andTitle:@"注册推送失败" andMessage:nil andTime:1];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
